<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="queryParams.patientName" placeholder="请输入患者姓名" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="性别" prop="sex" >
          <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable style="width: 200px">
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="table-wrapper">
      <el-table v-loading="loading" :data="patientList">
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="avatar" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar || '/static/default-avatar.png'" />
          </template>
        </el-table-column>
        <el-table-column prop="patientName" label="姓名" />
        <el-table-column prop="sex" label="性别">
          <template #default="{ row }">
            {{ row.sex === '0' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄">
          <template #default="{ row }">
            {{ calculateAge(row.age) }}岁
          </template>
        </el-table-column>
        <el-table-column prop="visitCount" label="问诊次数" />
        <el-table-column prop="visitTime" label="最近问诊">
          <template #default="{ row }">
            {{ formatDate(row.visitTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">查看问诊</el-button>
            <el-button type="primary" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="问诊记录" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="患者姓名">{{ detailData.patientName }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ detailData.sex === '0' ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ calculateAge(detailData.age) }}岁</el-descriptions-item>
        <el-descriptions-item label="问诊次数">{{ detailData.visitCount }}</el-descriptions-item>
        <el-descriptions-item label="最近问诊">{{ formatDate(detailData.visitTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { getPatientList, getPatientDetail, deletePatient } from '@/api/patient'
import { ElMessage, ElMessageBox } from 'element-plus'

interface PatientDetail {
  recordId: number
  userId: number
  patientName: string
  sex: string
  age: string
  avatar: string
  unreadCount: number
  visitCount: number
  visitTime: string
}

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  patientName: '',
  sex: undefined as string | undefined
})

const loading = ref(false)
const total = ref(0)
const patientList = ref<PatientDetail[]>([])
const detailVisible = ref(false)
const detailData = ref<PatientDetail>({
  recordId: 0,
  userId: 0,
  patientName: '',
  sex: '',
  age: '',
  avatar: '/static/default-avatar.png',
  unreadCount: 0,
  visitCount: 0,
  visitTime: ''
})

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 计算年龄
const calculateAge = (birthday: string) => {
  if (!birthday) return 0
  const today = new Date()
  const birthDate = new Date(birthday)
  let age = today.getFullYear() - birthDate.getFullYear()
  const m = today.getMonth() - birthDate.getMonth()
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  return age
}

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getPatientList(queryParams)
    if(res.code == 200) {
      // 转换新数据
      const newList = res.rows.map(item => ({
        recordId: item.recordId,
        userId: item.userId,
        patientName: item.patientName,
        sex: item.sex,
        age: item.age,
        avatar: item.avatar || '/static/default-avatar.png',
        unreadCount: item.unreadCount || 0,
        visitCount: item.visitCount || 1,
        visitTime: item.visitTime
      }))
      
      patientList.value = newList
      total.value = res.total
    }
  } catch (error) {
    console.error('获取患者列表失败', error)
    ElMessage.error('获取列表失败')
  }
  loading.value = false
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.patientName = ''
  queryParams.sex = undefined
  handleQuery()
}

// 查看详情
const handleDetail = async (row: PatientDetail) => {
  try {
    const res = await getPatientDetail(row.recordId)
    if (res.code == 200) {
      detailData.value = res.data
      detailVisible.value = true
    }
  } catch (error) {
    console.error(error)
  }
}

// 删除
const handleDelete = (row: PatientDetail) => {
  ElMessageBox.confirm('确认要删除该患者记录吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deletePatient(row.recordId)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      }
    } catch (error) {
      console.error(error)
    }
  }).catch(() => {})
}

// 分页
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .table-wrapper {
    .el-pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }
}
</style> 